package com.acme.bankapp.domain.bank;

import java.io.Serializable;

import com.acme.bankapp.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

/**
 * This class represents bank and allow you to add clients to the bank
 * 
 * @author Anton Kotov
 * 
 */
@SuppressWarnings("serial")
public class Bank implements Serializable {
    private Client[] clients;
    private ClientRegistrationListener[] listeners;

    public Bank(ClientRegistrationListener... listeners) {
	this.listeners = listeners;
    }

    public Client[] getClients() {
	if (clients == null) {
	    return null;
	}

	Client[] newClients = new Client[clients.length];
	System.arraycopy(clients, 0, newClients, 0, clients.length);
	return newClients;
    }

    public Bank addClient(Client client) throws ClientExistsException {
	if (clients == null) {
	    clients = new Client[1];
	    clients[0] = client;
	} else {
	    for (Client c : clients) {
		if (c.getName().equals(client.getName())) {
		    throw new ClientExistsException("Client with name '"
			    + client.getName() + "' already exists");
		}
	    }
	    Client[] newClients = new Client[clients.length + 1];
	    System.arraycopy(clients, 0, newClients, 0, clients.length);
	    newClients[clients.length] = client;
	    clients = newClients;
	}

	for (ClientRegistrationListener listener : listeners) {
	    listener.onClientAdded(client);
	}

	return this;
    }

    public Bank addClientRegistrationListener(
	    ClientRegistrationListener listener) {
	if (listeners == null) {
	    listeners = new ClientRegistrationListener[1];
	    listeners[0] = listener;
	} else {
	    ClientRegistrationListener[] newListeners = new ClientRegistrationListener[listeners.length + 1];
	    System.arraycopy(listeners, 0, newListeners, 0, listeners.length);
	    newListeners[listeners.length] = listener;
	    listeners = newListeners;
	}

	return this;
    }
}
